package com.china08.yxyapi.api.manage.edu.platform.resource;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.entity.es.ElasticYxyResResource;
import com.china08.yxyapi.model.YxyApiPageReqModel;
import com.china08.yxyapi.service.yxyresource.YxyResourceBaseService;
import com.china08.yxyapi.util.DateToolUtils;

import io.swagger.annotations.ApiOperation;

/**
 * 教育局平台办公 资源管理 搜索
 * 
 */
@CrossOrigin
@RestController("EduResourceSrhController")
public class ResourceSrhController extends YxyApiBaseController {

    // @Autowired
    // private YxyResourceService yxyResourceService;

    @Autowired
    private YxyResourceBaseService yxyResourceBaseService;

    @ApiOperation(value = "教育局 查询资源")
    @ResponseBody
    @RequestMapping(value = "/api_yw/manage/edu/platform/resource", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Page<RespModel> precess(HttpServletRequest request, HttpServletResponse response,
            @RequestBody ReqModel reqModel) throws IllegalAccessException, InvocationTargetException {

        Integer status = reqModel.status;
        String phase = reqModel.phase;
        String subject = reqModel.subject;
        String keyword = reqModel.keyword;

        Integer level = getProfile(request, response).getSchoolBureauLevel();

        String key = "";
        if (level == 0) {
            key = getProfile(request, response).getSchoolAreaIdDistrict();
        } else if (level == 1) {
            key = getProfile(request, response).getSchoolAreaIdCity();
        } else if (level == 2) {
            key = getProfile(request, response).getSchoolAreaIdProvince();
        }

        Pageable pageable = null;
        if (StringUtils.isNotBlank(reqModel.keyword)) {
            keyword = keyword.toLowerCase();
            pageable = new PageRequest(reqModel.page, reqModel.size);

        } else {
            pageable = reqModel.getPageable(Direction.fromString(reqModel.order), reqModel.field);
        }
        BoolQueryBuilder bool = new BoolQueryBuilder();

        // 区域
        BoolQueryBuilder areBuilder = new BoolQueryBuilder();
        TermQueryBuilder builderprovince = new TermQueryBuilder("provinceCode", key);
        TermQueryBuilder buildercity = new TermQueryBuilder("cityCode", key);
        TermQueryBuilder builderdistrict = new TermQueryBuilder("districtCode", key);
        areBuilder.should(builderprovince);
        areBuilder.should(buildercity);
        areBuilder.should(builderdistrict);
        bool.must(areBuilder);
        // 只可以查看共享到教育云的。
        TermQueryBuilder publicBuilder = new TermQueryBuilder("viewScope", 2);
        bool.must(publicBuilder);

        // 刨除已经删除的
        TermQueryBuilder isDelete = new TermQueryBuilder("isDelete", 0);
        bool.must(isDelete);

        // 因为微课和资源在一张表中所以刨除微课的
        TermQueryBuilder builderTypeNot = new TermQueryBuilder("typeId", "yx14");
        bool.mustNot(builderTypeNot);

        // 审核状态
        if (status != null && status != -1) {
            TermQueryBuilder builder = new TermQueryBuilder("status", status);
            bool.must(builder);
        }
        // 学段
        if (StringUtils.isNotBlank(phase) && !StringUtils.equals("all", phase)) {
            TermQueryBuilder builder = new TermQueryBuilder("phaseIdList", phase);
            bool.must(builder);
        }
        // 学科
        if (StringUtils.isNotBlank(subject) && !StringUtils.equals("all", subject)) {
            TermQueryBuilder builder = new TermQueryBuilder("subjectIdList", subject);
            bool.must(builder);
        }

        // 是否加精
        if (StringUtils.isNotBlank(reqModel.quality) && !StringUtils.equals("all", reqModel.quality)) {
            if (status == 1) {
                if (StringUtils.equals("0", reqModel.quality)) {
                    TermQueryBuilder builder = new TermQueryBuilder("isHighQualityQy", 1);
                    bool.mustNot(builder);
                } else {
                    TermQueryBuilder builder = new TermQueryBuilder("isHighQualityQy",
                            Integer.parseInt(reqModel.quality));
                    bool.must(builder);
                }

            }
        }
        Page<ElasticYxyResResource> page = yxyResourceBaseService.getPageKeyword(bool, keyword, 3, pageable);
        // ##
        List<RespModel> list = new ArrayList<ResourceSrhController.RespModel>();
        for (ElasticYxyResResource elasticYxyResResource : page) {
            RespModel model = new RespModel();
            BeanUtils.copyProperties(model, elasticYxyResResource);
            model.setUploadTimeFormat(elasticYxyResResource.getUploadTime() != null
                    ? DateToolUtils.format(elasticYxyResResource.getUploadTime(), DateToolUtils.FORMAT_SHORT_YMD) : "");
            model.setAuditDateFormat(
                    DateToolUtils.format(elasticYxyResResource.getLastModifiedDate(), DateToolUtils.FORMAT_SHORT_YMD));
            // 所属
            model.setBookContentNames(elasticYxyResResource.getBookContentNameList());
            model.setExtension(elasticYxyResResource.getExtension());
            list.add(model);
        }

        Page<RespModel> respModel = new PageImpl<ResourceSrhController.RespModel>(list, pageable,
                page.getTotalElements());

        return respModel;
    }

    public static class RespModel {
        public String title;
        public String typeName;
        // 学段 + 学科 + 版本 + 侧别（课本） + 目录
        public List<String> bookContentNames;
        public String uploaderSchoolName;
        public String uploaderName;
        public String auditUserName;
        public String auditSchoolName;
        public String uploadTimeFormat;
        public String formatId;
        public String id;
        // 审核状态 0：待审核 1：已通过 2：未通过 3：已下架
        public Integer status;
        public String remark;
        // 审核时间（最后一次更改时间）
        public String auditDateFormat;
        public String extension;
        // 区域精品 0 否 1是
        public Integer isHighQualityQy = 0;

        // 云校精品 0否 1是
        public Integer isHighQualityYx = 0;

        public String getExtension() {
            return extension;
        }

        public void setExtension(String extension) {
            this.extension = extension;
        }

        public String getAuditDateFormat() {
            return auditDateFormat;
        }

        public void setAuditDateFormat(String auditDateFormat) {
            this.auditDateFormat = auditDateFormat;
        }

        public String getRemark() {
            return remark;
        }

        public void setRemark(String remark) {
            this.remark = remark;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public String getTypeName() {
            return typeName;
        }

        public void setTypeName(String typeName) {
            this.typeName = typeName;
        }

        public List<String> getBookContentNames() {
            return bookContentNames;
        }

        public void setBookContentNames(List<String> bookContentNames) {
            this.bookContentNames = bookContentNames;
        }

        public String getUploaderSchoolName() {
            return uploaderSchoolName;
        }

        public void setUploaderSchoolName(String uploaderSchoolName) {
            this.uploaderSchoolName = uploaderSchoolName;
        }

        public String getUploaderName() {
            return uploaderName;
        }

        public void setUploaderName(String uploaderName) {
            this.uploaderName = uploaderName;
        }

        public String getAuditUserName() {
            return auditUserName;
        }

        public void setAuditUserName(String auditUserName) {
            this.auditUserName = auditUserName;
        }

        public String getAuditSchoolName() {
            return auditSchoolName;
        }

        public void setAuditSchoolName(String auditSchoolName) {
            this.auditSchoolName = auditSchoolName;
        }

        public String getUploadTimeFormat() {
            return uploadTimeFormat;
        }

        public void setUploadTimeFormat(String uploadTimeFormat) {
            this.uploadTimeFormat = uploadTimeFormat;
        }

        public String getFormatId() {
            return formatId;
        }

        public void setFormatId(String formatId) {
            this.formatId = formatId;
        }

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public Integer getStatus() {
            return status;
        }

        public void setStatus(Integer status) {
            this.status = status;
        }

        public Integer getIsHighQualityQy() {
            return isHighQualityQy;
        }

        public void setIsHighQualityQy(Integer isHighQualityQy) {
            this.isHighQualityQy = isHighQualityQy;
        }

        public Integer getIsHighQualityYx() {
            return isHighQualityYx;
        }

        public void setIsHighQualityYx(Integer isHighQualityYx) {
            this.isHighQualityYx = isHighQualityYx;
        }

    }

    public static class ReqModel extends YxyApiPageReqModel {

        // 区域代
        public String areaId;
        // - 1 为全部
        public Integer status;

        // 是否加精 0否 1是
        public String quality;

        public String phase;

        public String subject;

        public String keyword;

        // Desc And Asc
        public String order;

        // Desc And Asc
        public String field;

    }
}
